import {
    controller,
    get,
    post,
    del,
    auth,
    admin,
    required
} from './../lib/decorator.js'
import {
    getAllMovies,
    findAndRemove

} from './../service/movie'
import {checkPassword} from './../service/admin'

@controller('/admin')
export class adminController {
    @get('/movie/list')
    @auth
    @admin('admin')
    async getMovieList(ctx, next) {
        const {type}=ctx.query
        const movies = await getAllMovies(type)
        ctx.body = {
            success: true,
            data: movies
        }
    }
    @del('/movies')
    @required({
        query: ['id']
    })
    async remove(ctx, next) {
        const id = ctx.query.id
        await findAndRemove(id)
        const movies = await getAllMovies()
        ctx.body = {
            data: movies,
            success: true
        }
    }
    @post('/login')
    @required({
        body: ['username', 'password']
    })
    async login(ctx, next) {
      
        const {
            username,
            password
        } = ctx.request.body
        
        const matchData = await checkPassword(username, password)

        if (!matchData.user) {
            return (ctx.body = {


                success: false,
                err: '用户不存在'
            })
        }
        console.log(matchData)
        if (matchData.match) {
            ctx.session.user = {
                _id: matchData.user._id,
                email: matchData.user.email,
                role: matchData.user.role,
                username: matchData.user.username
            }

            return (ctx.body = {
                success: true
            })
        }

        return (ctx.body = {
            success: false,
            err: '密码不正确'
        })
    }

}